<template>
    <popup  ref="popupRef" title="关联微信号列表"    :async="true"   width="60%">
        <div class="search-container mb-4">
            <el-input
                v-model="searchKeyword"
                placeholder="搜索微信号"
                prefix-icon="el-icon-search"
                clearable
                @input="handleSearch"
            >
                <template #prefix>
                    <el-icon><Search /></el-icon>
                </template>
            </el-input>
        </div>
        <el-card class="!border-none" shadow="never" style="max-height: 500px; overflow-y: auto;">
            <div class="mb-3 text-left total-count">
                共 <span class="font-bold text-primary">{{ filteredList.length }}</span> 条数据
                <el-button 
                    type="primary" 
                    size="small" 
                    class="ml-3"
                    @click="toggleAllWechat"
                >
                    {{ showAllWechat ? '隐藏所有微信号' : '显示所有微信号' }}
                </el-button>

                <el-button 
                    type="primary" 
                    size="small" 
                    class="ml-3"
                    @click="exportToExcel"
                    :loading="exportLoading"
                >
                    <el-icon class="mr-1">
                        <Download />
                    </el-icon>
                    导出表格
                </el-button>

                <el-button 
                    type="primary" 
                    size="small" 
                    class="ml-3"
                    @click="batchCopyWechat"
                    :loading="copyLoading"
                >
                    <el-icon class="mr-1">
                        <CopyDocument />
                    </el-icon>
                    批量复制
                </el-button>
            </div>
            <el-table :data="filteredList" height="450" header-align="center"  v-loading="loading">
                <el-table-column label="微信号" align="center">
                    <template #default="{ row }">
                        <div class="flex items-center justify-center">
                            <span v-if="showAllWechat || row.showWechat">{{ row.user_id }}</span>
                            <span v-else>{{ maskWechat(row.user_id) }}</span>
                            <el-button
                                type="text"
                                size="small"
                                class="ml-2 eye-button"
                                @click="toggleWechat(row)"
                            >
                                <el-icon>
                                    <View v-if="showAllWechat || row.showWechat" />
                                    <Hide v-else />
                                </el-icon>
                            </el-button>
                        </div>
                    </template>
                </el-table-column>
            </el-table>
        </el-card>
    </popup>
</template>

<script setup lang="ts">
import { Search, View, Hide, Download, CopyDocument } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'
import Popup from '@/components/popup/index.vue'
import { usePaging } from '@/hooks/usePaging'
import { apiTencentAdvertisingUserAdListBindWechatLists } from '@/api/tencent_advertising_user_ad_list'


const popupRef = shallowRef<InstanceType<typeof Popup>>()
const mode = ref('wechat_list')
const props = defineProps({
    ad_group_id: String
})
// 添加loading状态
const loading = ref(false)
// 存储所有数据
const allData = ref<any[]>([])
// 搜索关键词
const searchKeyword = ref('')
// 控制是否显示所有微信号
const showAllWechat = ref(false)
// 导出加载状态
const exportLoading = ref(false)
// 复制加载状态
const copyLoading = ref(false)

// 过滤后的数据
const filteredList = computed(() => {
    if (!searchKeyword.value) {
        return allData.value
    }
    return allData.value.filter(item => 
        item.user_id && item.user_id.toLowerCase().includes(searchKeyword.value.toLowerCase())
    )
})

/**
 * 隐藏微信号，只显示前3位和后2位
 */
const maskWechat = (wechat: string) => {
    if (!wechat || wechat.length <= 5) return wechat
    return wechat.substring(0, 3) + '*'.repeat(wechat.length - 5) + wechat.substring(wechat.length - 2)
}

/**
 * 切换单个微信号的显示状态
 */
const toggleWechat = (row: any) => {
    row.showWechat = !row.showWechat
}

/**
 * 切换所有微信号的显示状态
 */
const toggleAllWechat = () => {
    showAllWechat.value = !showAllWechat.value
    // 重置单个微信号的显示状态
    allData.value.forEach(item => {
        item.showWechat = false
    })
}

/**
 * 获取所有微信号列表数据
 */
 const getAllLists = async () => {
    loading.value = true
    try {
        const res = await apiTencentAdvertisingUserAdListBindWechatLists({
            ad_group_id: props.ad_group_id,
            page: 1,
            limit: 9999 // 设置一个较大的值，一次获取所有数据
        })
        allData.value = res || []
    } catch (error) {
        console.error('获取微信号列表失败:', error)
    }finally {
        loading.value = false
    }
}

/**
 * 处理搜索功能
 */
 const handleSearch = () => {
    // 搜索功能已通过计算属性实现，这里不需要额外处理
}

/**
 * 导出CSV表格
 */
const exportToExcel = async () => {
    if (filteredList.value.length === 0) {
        ElMessage.warning('没有数据可导出')
        return
    }

    exportLoading.value = true
    try {
        // 准备导出数据
        const exportData = filteredList.value.map((item, index) => ({
            '序号': index + 1,
            '微信号': showAllWechat.value || item.showWechat ? item.user_id : maskWechat(item.user_id),
            '完整微信号': item.user_id, // 始终导出完整微信号
            '显示状态': showAllWechat.value || item.showWechat ? '显示' : '隐藏'
        }))

        // 创建CSV内容
        const headers = ['序号', '微信号', '完整微信号', '显示状态']
        const csvContent = [
            headers.join(','),
            ...exportData.map(row => [
                row['序号'],
                `"${row['微信号']}"`,
                `"${row['完整微信号']}"`,
                row['显示状态']
            ].join(','))
        ].join('\n')

        // 添加BOM以支持中文
        const BOM = '\uFEFF'
        const csvWithBOM = BOM + csvContent

        // 生成文件名
        const timestamp = new Date().toISOString().slice(0, 19).replace(/:/g, '-')
        const fileName = `微信号列表_${timestamp}.csv`

        // 导出文件
        const blob = new Blob([csvWithBOM], { type: 'text/csv;charset=utf-8;' })
        const url = window.URL.createObjectURL(blob)
        const link = document.createElement('a')
        link.href = url
        link.download = fileName
        link.click()
        window.URL.revokeObjectURL(url)

        ElMessage.success('导出成功')
    } catch (error) {
        console.error('导出失败:', error)
        ElMessage.error('导出失败，请重试')
    } finally {
        exportLoading.value = false
    }
}

/**
 * 批量复制微信号
 */
const batchCopyWechat = async () => {
    if (filteredList.value.length === 0) {
        ElMessage.warning('没有数据可复制')
        return
    }

    copyLoading.value = true
    try {
        // 提取所有微信号，用换行符分隔
        const wechatList = filteredList.value.map(item => item.user_id).join('\n')
        
        // 复制到剪贴板
        await navigator.clipboard.writeText(wechatList)
        
        ElMessage.success(`成功复制 ${filteredList.value.length} 个微信号到剪贴板`)
    } catch (error) {
        console.error('复制失败:', error)
        
        // 降级方案：使用传统方法复制
        try {
            const textArea = document.createElement('textarea')
            textArea.value = filteredList.value.map(item => item.user_id).join('\n')
            document.body.appendChild(textArea)
            textArea.select()
            document.execCommand('copy')
            document.body.removeChild(textArea)
            
            ElMessage.success(`成功复制 ${filteredList.value.length} 个微信号到剪贴板`)
        } catch (fallbackError) {
            console.error('降级复制也失败:', fallbackError)
            ElMessage.error('复制失败，请重试')
        }
    } finally {
        copyLoading.value = false
    }
}

const open = (type = 'placement_log') => {
    mode.value = type
    popupRef.value?.open()
}

onMounted(() => {
    getAllLists()
    open()
})

defineExpose({
    open
})
</script>

<style scoped>
.search-container {
    padding: 0 10px;
}

.total-count {
    font-size: 16px;
    padding-left: 10px;
    color: #606266;
}

.total-count .text-primary {
    font-size: 18px;
    color: #409EFF;
}

.eye-button {
    font-size: 16px;
    width: 24px;
    height: 24px;
    padding: 0;
}

.eye-button .el-icon {
    font-size: 16px;
}
</style>